﻿using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.IO;

public class BsonSerializer
{

    public static byte[] PackBson(object obj)
    {
        byte[] serializedData = new byte[] { };
        using (var stream = new MemoryStream())
        {
            using (BsonWriter writer = new BsonWriter(stream))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, obj);
            }
            return stream.ToArray();
        }
    }

    public static T UnpackBson<T>(byte[] data)
    {
        using (var stream = new MemoryStream(data))
        {
            using (BsonReader reader = new BsonReader(stream))
            {
                JsonSerializer serializer = new JsonSerializer();
                return serializer.Deserialize<T>(reader);
            }
        }
    }

    public static void PackBsonToFile(string path, object obj, string name)
    {
        if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }
        string filePath = path + "/" + name + ".bson";
        using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
        {
            BinaryWriter writer = new BinaryWriter(fs);
            writer.Write(PackBson(obj));
            writer.Close();
            fs.Close();
        }
    }

    public static T UnpackBsonFromFile<T>(string path, string name)
    {
        string filePath = path + "/" + name + ".bson";
        using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            BinaryReader reader = new BinaryReader(fs);
            return UnpackBson<T>(reader.ReadBytes((int)reader.BaseStream.Length));
        }
    }
}
